package com.zhe.zheblogmaster.handler.admin;

import com.github.pagehelper.PageInfo;
import com.zhe.zheblogmaster.entity.BlogCategory;
import com.zhe.zheblogmaster.service.BlogCategoryService;
import com.zhe.zheblogmaster.util.ResultBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @author WHAOU
 * @date 2021/9/18
 * @email whaou@qq.com
 */
@Controller
@ResponseBody
@RequestMapping("/admin/category")
public class CategoryHandler {
    @Autowired
    private BlogCategoryService categoryService;

    @GetMapping("/list")
    public ResultBody<PageInfo<BlogCategory>> getCategories(@RequestParam("pageNum") Integer pageNum) {
        PageInfo<BlogCategory> pageInfo = categoryService.getCategoryPage(pageNum);
        return ResultBody.successWithData(pageInfo);
    }

    @PostMapping("/add")
    public ResultBody<String> addCategory(@RequestParam("categoryName") String name,
                                          @RequestParam("categoryIcon") String icon) {

        if (!StringUtils.hasLength(name)) {
            return ResultBody.error("请输入分类名称！");
        }
        if (!StringUtils.hasLength(icon)) {
            return ResultBody.error("请选择分类图标！");
        }
        Boolean res = categoryService.addCategory(name, icon);
        if (res) {
            return ResultBody.successWithoutData();
        } else {
            return ResultBody.error("分类名称重复");
        }
    }

    @PostMapping("/update")
    public ResultBody<String> update(@RequestParam("categoryId") Integer id,
                                     @RequestParam("categoryName") String name,
                                     @RequestParam("categoryIcon") String icon) {
        if (!StringUtils.hasLength(name)) {
            return ResultBody.error("请输入分类名称！");
        }
        if (!StringUtils.hasLength(icon)) {
            return ResultBody.error("请选择分类图标！");
        }
        if (categoryService.updateCategory(id, name, icon)) {
            return ResultBody.successWithoutData();
        } else {
            return ResultBody.error("更新失败");
        }
    }

    @PostMapping("/delete")
    public ResultBody<String> delete(@RequestBody Integer[] ids) {
        if (ids == null || ids.length < 1) {
            return ResultBody.error("请选择要删除的记录");
        }
        int count = categoryService.deleteBatch(ids);
        if (count > 0) {
            return ResultBody.successWithData(String.valueOf(count));
        } else {
            return ResultBody.error("删除失败");
        }
    }
}
